import os
from django import http
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.ext import db
import dados
import simplejson as json

class AdminModel(webapp.RequestHandler):

	__tipoperfil__=0
	__ufperfil__=""
			
	def validaprofile(self):
		
		user = users.GetCurrentUser()
		p = self.response.out
		r = self.request
	
		if user:
		
			usuario = db.GqlQuery("SELECT * from Usuario where email=:1", user.email())
			rs = usuario.fetch(1)
			
			if len(rs)==0:
				self.redirect(users.create_login_url(self.request.uri))
			else:
				self.__tipoperfil__ = rs[0].perfil
				self.__ufperfil__ = rs[0].uf			
		else:
			self.redirect(users.create_login_url(self.request.uri))
		

class AdministraPontos(AdminModel):

	def get(self):
		self.validaprofile()
		valores={"uf": self.__ufperfil__, "pid": self.__tipoperfil__}
		path = os.path.join(os.path.dirname(__file__), 'templates/index_admin.html')
		self.response.out.write( template.render(path, valores))
			

class CadastraUsuario(AdminModel):

	def get(self):
		self.validaprofile()
		path = os.path.join(os.path.dirname(__file__), 'templates/index_cadusuario.html')
		self.response.out.write( template.render(path, {"msg":"0"}))
			
	def post(self):
	
		self.validaprofile()
		usuario = self.request.get("usuario","")
		email = self.request.get("email","")
		perfil = self.request.get("perfil",0)
		uf = self.request.get("uf","")
		
		msg={"msg":"0"}
		
		if usuario!="" and email!="" and perfil!=0 and uf!="":
		
			usuario = db.GqlQuery("SELECT * from Usuario where email=:1", email).get()
			
			if not usuario:
				a = dados.Usuario()
				a.nome = usuario
				a.email = email
				a.uf = uf
				a.perfil = int(perfil)
				a.put()
				
				msg["msg"]="1"
				
			else:
				msg["msg"]="2"
				
		else:
			msg["msg"]="3"
				
		path = os.path.join(os.path.dirname(__file__), 'templates/index_cadusuario.html')
		self.response.out.write( template.render(path, msg))
		
		
class JsonAdm(AdminModel):

	def get(self):
	
		p = self.response.out
		r = self.request
		
		acao = r.get("acao")
		
		saida={}
		item={}
		lista=[]
		
		saida["status"]=""
		
		if acao=="pontos":
		
			uf = r.get("uf")
			pid = r.get("pid")
			
			l=['N','E']
				
			if pid=="1":
				pontos = db.GqlQuery("SELECT * from Pontos WHERE status in :1", l)
			else:
				pontos = db.GqlQuery("SELECT * from Pontos WHERE status in :1 and uf=:2",l,uf)
				
			for a in pontos:
				item={}
				item["id"]=a.id
				item["latitude"]=a.ponto.lat
				item["longitude"]=a.ponto.lon
				item["nome"]=a.nome
				item["descricao"]=a.descricao
				item["alerta_velocidade"]=a.alerta_velocidade
				item["alerta_distancia"]=a.alerta_distancia
				item["id_categoria"]=a.id_categoria
				item["endereco"]=a.endereco
				item["cidade"]=a.cidade
				item["uf"]=a.uf
				lista.append(item)
			
			saida["status"]="ok"
			saida["pontos"]=lista
			
		p.write(json.dumps(saida))
			
	def post(self):
		
		acao = self.request.get("acao")
		saida={}
		saida["status"]=""
		
		if acao=="atualiza":
		
			pontos = json.loads( self.request.get("pontos") )
			
			for i in range(0, len(pontos)):
			
				ponto = db.GqlQuery("SELECT * from Pontos where id=:1", pontos[i]["id"]).get()
				if ponto:
					ponto.lat = pontos[i]["lat"];
					ponto.lon = pontos[i]["lng"];
					ponto.status = pontos[i]["status"]
					ponto.put()
					
			saida["status"]="ok"
		
		self.response.out.write(json.dumps(saida))
		
			
application = webapp.WSGIApplication(
                                     [('/aa/adm', AdministraPontos),
									 ('/aa/cad', CadastraUsuario),
									 ('/aa/json', JsonAdm)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()